package com.haople.sso.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.haople.sso.core.authentication.UserAuthorization;

@Controller
public class registerController {

	private static final Logger logger=Logger.getLogger(registerController.class);
	private static final String REGISTER_ERROR_MSG="register_error_msg";
	private static final String ERROR_MSG="error_msg";
	private static final String SSO_CAPTCHA="sso_captcha";
	
	@Autowired
	private UserAuthorization  userAuthorization;
	
	@RequestMapping(value = "/toRegister")
	public String toRegister() {
		return "register";
	}
	
	/**
	 * 注册用户信息
	 * @param userName
	 * @param password
	 * @param captcha
	 * @param redirectAttributes
	 * @param httpSession
	 * @return
	 */
	@RequestMapping(value = "/register", method = RequestMethod.POST)
	public String register(String userName, String password, String captcha, RedirectAttributes redirectAttributes,
			HttpSession httpSession) {
		try {
			if(StringUtils.isEmpty(userName)){
				redirectAttributes.addFlashAttribute(REGISTER_ERROR_MSG, "用户名为空！");
				return "redirect:/toRegister";
			}
			if(StringUtils.isEmpty(password)){
				redirectAttributes.addFlashAttribute(REGISTER_ERROR_MSG, "密码为空！");
				return "redirect:/toRegister";
			}
			if(StringUtils.isEmpty(captcha)){
				redirectAttributes.addFlashAttribute(REGISTER_ERROR_MSG, "验证码为空！");
				return "redirect:/toRegister";
			}
			String sessionCaptcha;
			if(StringUtils.isEmpty((sessionCaptcha=httpSession.getAttribute(SSO_CAPTCHA).toString())) || !captcha.toLowerCase().equals(sessionCaptcha.toLowerCase())){
				redirectAttributes.addFlashAttribute(REGISTER_ERROR_MSG, "验证码错误！");
				return "redirect:/toRegister";
			}
			if(userAuthorization.exist(userName)) {
				redirectAttributes.addFlashAttribute(REGISTER_ERROR_MSG, "此用户已经注册");
				return "redirect:/toRegister";
			}
			if(!userAuthorization.save(userName, password)) {
				redirectAttributes.addFlashAttribute(ERROR_MSG, "注册失败");
				return "redirect:/error";
			}
			return "redirect:/register-success";
		} catch (Exception e) {
			logger.error("------------用户注册异常--------------", e);
			redirectAttributes.addFlashAttribute(ERROR_MSG, "系统错误");
			return "redirect:/error";
		}
	}
	
	@RequestMapping("/register-success")
	public String register(Model model,String k,HttpServletRequest request,RedirectAttributes redirectAttributes){
		   return "register-success";
	}
}
